<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\User;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Scoreoff extends Backend
{

    /**
     * Scoreoff模型对象
     * @var \app\admin\model\Scoreoff
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Scoreoff;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function shenhe($ids=null){
        $id = $this->request->post('id');
        $status = $this->request->post('status');
        if(!$id){
            $list = Db::name("scoreoff")->alias('r')
                ->field("r.*,c.name as course_name")

                ->join("course c",'r.course_id = c.id', 'LEFT')

                ->where(['r.id'=>$ids])
                ->find();

            $this->view->assign("ids", $ids);
            $this->view->assign( 'row', $list);
            return $this->view->fetch();
        }
        // exit;
        $data = Db::name("scoreoff")->where(['id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        //$score = Db::name("user")->where(['id'=>$data['user_id']])->value("score");
        $merchant_score = self::getMerchantScoreone($data['user_id'],$data['merchant_user_id']);
        if($merchant_score < $data['score']){
            $this->error("积分不足核销失败");
        }
        if($status == 1){
            \app\common\model\User::score(-$data['score'],$data['user_id'], "积分核销减少积分",1,$data['merchant_user_id'],$data['course_id']);
            \app\common\model\User::score($data['score'],$data['merchant_user_id'], "积分核销");
            Db::name("scoreoff")->where(['id'=>$id])->update(['status'=>1]);
        }else{
            Db::name("scoreoff")->where(['id'=>$id])->update(['status'=>2]);
        }


        $this->success("操作成功");
    }
    public static function getMerchantScoreone($user_id,$merchant_user_id){
        $list = Db::name("user_score_log")->where(['user_id'=>$user_id,'merchant_user_id'=>$merchant_user_id,'is_fixed'=>1])->select();
        $vlu = 0;
        if($list){
            foreach ($list as $k=>$v){
                if($v['before'] > $v['after']){
                    $vlu -= abs($v['score']);
                }else{
                    $vlu += abs($v['score']);
                }
            }
        }
        return $vlu;
    }
}
